<?php
namespace app\http;

use app\common\model\Brand;
use app\common\model\ComputeDetail;
use app\common\model\Dose;
use app\common\model\Meal;
use app\common\model\Menu;
use app\common\model\Offer;
use app\common\model\OfferDetail;
use app\common\model\ProjectLog;
use app\common\model\Send;
use app\common\model\Spec;
use app\common\model\Type;
use think\facade\Config;
//require_once '/vendor/autoload.php';
// 导入要请求接口对应的Request类
// 导入可选配置类
use think\worker\Server;
use Workerman\Lib\Timer;

class Caigou extends Server
{
                                                    //protected $processes = 4;
    protected $socket = 'websocket://0.0.0.0:2005'; //正式
                                                    //protected $socket = 'tcp://0.0.0.0:2008'; //测试
    /**
     * 每个进程启动
     * @param $worker
     */
    public function onWorkerStart($worker)
    {

        Timer::add(1, [$this, 'project_log']);

    }

    public function project_log()
    {
        echo '[生成配送单]--开始运行';
        echo "\r\n";
        $list = ProjectLog::where('status', 2)->where('tag', 0)->select();
        foreach ($list as $k => $v) {
            $this->send($v['id']);
            ProjectLog::where('id', $v['id'])->update(['tag' => 1]);
        }

    }

    public function send($project_log_id)
    {

        $config = Config::get('site.site');

        $project_log = ProjectLog::where('id', $project_log_id)->findOrEmpty();
        if (! $project_log->isEmpty()) {
            $detail  = [];
            $detail0 = [];
            $offer   = [];
            //$dose_id_list = [];
            foreach ($project_log['detail'] as $key => $value) {

                $compute_detail_list = ComputeDetail::where('compute_id', $value['compute_id'])->select()->toArray();
                $dose_id_list        = array_column($compute_detail_list, 'dose_id');
                $type_id_list        = ['1281', '555', '1073', '557'];
                $type                = Type::where('name', $value['name'])->where('tag', 1)->find();
                if (in_array($type['id'], $type_id_list)) {
                    $detail0[] = [
                        'type_id'   => Type::where('name', $value['name'])->where('parent_id', '<>', 0)->where('tag', 1)->value('id'),
                        'spec_id'   => Spec::where('name', $value['spec'])->value('id'),
                        'brand_id'  => Brand::where('name', $value['brand'])->value('id'),

                        'price'     => $value['money'],
                        'shou_num'  => 0,
                        'wei_num'   => 0,
                        'avg_price' => 0,

                        'status'    => 0,
                        'beizhu'    => '',
                        //'school_id' => $school_id,

                    ];
                } else {
                    $detail[] = [
                        'type_id'   => Type::where('name', $value['name'])->where('parent_id', '<>', 0)->where('tag', 1)->value('id'),
                        'spec_id'   => Spec::where('name', $value['spec'])->value('id'),
                        'brand_id'  => Brand::where('name', $value['brand'])->value('id'),

                        'price'     => $value['money'],
                        'shou_num'  => 0,
                        'wei_num'   => 0,
                        'avg_price' => 0,

                        'status'    => 0,
                        'beizhu'    => '',
                        //'school_id' => $school_id,

                    ];
                }

                $price   = round($value['money'] + ($value['money'] * ($config['price'] / 100)), 2);
                $offer[] = [
                    'type_id'  => Type::where('name', $value['name'])->where('parent_id', '<>', 0)->where('tag', 1)->value('id'),
                    'spec_id'  => Spec::where('name', $value['spec'])->value('id'),
                    'brand_id' => Brand::where('name', $value['brand'])->value('id'),

                    'price'    => $price,

                    'status'   => 0,
                    //'school_id' => $school_id,

                ];

                //}

            }

            $dose_list       = Dose::whereIn('id', $dose_id_list)->select()->toArray();
            $offer_detail_id = [];
            $school_id       = [];
            foreach ($dose_list as $dose_key => $dose_value) {
                //ComputeDetail::where('dose_id', $dose_value['id'])->update(['user_id' => $project_log['user_id']]);
                $meal_list = [];
                $type_list = [];
                foreach ($dose_value['detail'] as $detail_key => $detail_value) {

                    $meal_list[] = [
                        'meal_id' => $detail_value['meal_id'],
                        'num'     => $detail_value['num'],
                        'dose_id' => $dose_value['id'],
                        'tag'     => $dose_value['tag'],
                    ];
                }

                foreach ($dose_value['detail2'] as $detail2_key => $detail2_value) {
                    if (! isset($detail2_value['num'])) {
                        $detail2_value['num'] = 0;
                    }
                    if ($detail2_value['brand_id'] == 22 && $detail2_value['spec_id'] == 214) {
                        $detail2_num      = round($detail2_value['num'] / 500, 2);
                        $detail2_spec_id  = 4;
                        $detail2_brand_id = 3;
                    } else {
                        $detail2_num      = $detail2_value['num'];
                        $detail2_spec_id  = $detail2_value['spec_id'];
                        $detail2_brand_id = $detail2_value['brand_id'];
                    }

                    $type_list[] = [
                        'type_id'  => $detail2_value['type_id'],
                        'spec_id'  => $detail2_spec_id,
                        'brand_id' => $detail2_brand_id,
                        'num'      => $detail2_num,
                        'beizhu'   => $detail2_value['beizhu'] ?? '',
                        'dose_id'  => $dose_value['id'],
                    ];
                }
                foreach ($meal_list as $meal_key => $meal_value) {

                    $meal = Meal::where('id', $meal_value['meal_id'])->findOrEmpty();
                    if (! $meal->isEmpty()) {
                        foreach ($meal['detail'] as $meal_detail_key => $meal_detail_value) {
                            $menu_list[] = $meal_detail_value['menu_id'];
                            $menu        = Menu::where('id', $meal_detail_value['menu_id'])->findOrEmpty();
                            if (! $menu->isEmpty()) {
                                foreach ($menu['detail'] as $menu_detail_key => $menu_detail_value) {
                                    if ($meal_value['num'] == '') {
                                        $meal_value['num'] = 0;
                                    }
                                    if ($meal_value['tag'] == 1) {
                                        $meal_value['num'] = 1;
                                    }
                                    if (! isset($menu_detail_value['num']) || $menu_detail_value['num'] == '') {
                                        $menu_detail_value['num'] = 0;
                                    }
                                    if (! is_numeric($menu_detail_value['num'])) {
                                        $menu_detail_value['num'] = 0;
                                    }
                                    if (isset($menu_detail_value['beizhu']) && $menu_detail_value['beizhu'] != '') {
                                        $beizhu = $menu_detail_value['beizhu'];
                                    } else {
                                        $beizhu = '';
                                    }
                                    if ($menu_detail_value['brand_id'] == 22 && $menu_detail_value['spec_id'] == 214) {
                                        $menu_detail_num      = round($menu_detail_value['num'] / 500, 2);
                                        $menu_detail_spec_id  = 4;
                                        $menu_detail_brand_id = 3;
                                    } else {
                                        $menu_detail_num      = $menu_detail_value['num'];
                                        $menu_detail_spec_id  = $menu_detail_value['spec_id'];
                                        $menu_detail_brand_id = $menu_detail_value['brand_id'];
                                    }
                                    if ($menu_detail_value['type_id'] == 197 || $menu_detail_value['type_id'] == 7) {
                                        $menu_detail_value['type_id'] = 410;
                                    }
                                    if ($menu_detail_value['type_id'] == 196) {
                                        $menu_detail_value['type_id'] = 411;
                                    }
                                    if ($menu_detail_value['type_id'] == 195) {
                                        $menu_detail_value['type_id'] = 409;
                                    }

                                    $type_list[] = [
                                        'type_id'  => $menu_detail_value['type_id'],
                                        'num'      => $meal_value['num'] * $menu_detail_num,
                                        'spec_id'  => $menu_detail_spec_id,
                                        'brand_id' => $menu_detail_brand_id,
                                        'beizhu'   => $beizhu,
                                        'dose_id'  => $meal_value['dose_id'],
                                    ];
                                }
                            }
                        }
                    }
                }

                $send_detail = $this->array_do3($detail, $type_list);
                foreach ($send_detail as $dk => $dv) {
                    $send_detail[$dk]['money'] = round($dv['price'] * $dv['num'], 2);
                }
                $send_detail = $this->array_do($send_detail);

                $send_detail0 = $this->array_do3($detail0, $type_list);
                foreach ($send_detail0 as $dk2 => $dv2) {
                    $send_detail0[$dk2]['money'] = round($dv2['price'] * $dv2['num'], 2);
                }
                $send_detail0 = $this->array_do($send_detail0);

                $offer_details = $this->array_do3($offer, $type_list);
                foreach ($offer_details as $ok => $ov) {
                    $offer_details[$ok]['money'] = round($ov['price'] * $ov['num'], 2);
                    ComputeDetail::where('dose_id', $dose_value['id'])
                        ->where('type_id', $ov['type_id'])->where('school_id', $dose_value['school_id'])->update(['user_id' => $project_log['user_id'], 'send_time' => $dose_value['week']]);
                }
                $offer_details = $this->array_do($offer_details);
                if (! empty($offer_details)) {
                    $find_offer = OfferDetail::where('school_id', $dose_value['school_id'])->where('send_time', strtotime($dose_value['week']))->findOrEmpty();
                    if ($find_offer->isEmpty()) {
                        foreach ($offer_details as $ok => $ov) {
                            $offer_details[$ok]['money'] = round($ov['price'] * $ov['num'], 2);
                        }
                        $offer_detail_data = [
                            'name'      => $dose_value['week'] . '报价单',
                            'send_id'   => 0,
                            'code'      => date('YmdHis') . rand(00000, 99999),
                            'money'     => array_sum(array_column($offer_details, 'money')),
                            'detail'    => $offer_details,
                            'send_time' => $dose_value['week'],
                            'school_id' => $dose_value['school_id'],
                        ];
                        $offer_detail           = OfferDetail::create($offer_detail_data);
                        $offer_detail_id[]      = $offer_detail->id;
                        $offer_detail_result_id = $offer_detail->id;
                        $school_id[]            = $dose_value['school_id'];
                    } else {
                        $offer_details = array_merge($offer_details, $find_offer['detail']);
                        foreach ($offer_details as $ok => $ov) {
                            $offer_details[$ok]['money'] = round($ov['price'] * $ov['num'], 2);
                        }
                        $offer_detail_data = [
                            'name'      => $dose_value['week'] . '报价单',
                            'send_id'   => 0,
                            'code'      => date('YmdHis') . rand(00000, 99999),
                            'money'     => array_sum(array_column($offer_details, 'money')),
                            'detail'    => $offer_details,
                            'send_time' => $dose_value['week'],
                            'school_id' => $dose_value['school_id'],
                        ];
                        $offer_detail           = $find_offer->save($offer_detail_data);
                        $offer_detail_id[]      = $find_offer->id;
                        $offer_detail_result_id = $find_offer->id;
                        $school_id[]            = $dose_value['school_id'];
                    }
                    if (! empty($send_detail)) {

                        $find_send = Send::where('school_id', $dose_value['school_id'])->where('send_time', strtotime($dose_value['week']))->where('user_id', $project_log['user_id'])->findOrEmpty();
                        if ($find_send->isEmpty()) {
                            foreach ($send_detail as $dk => $dv) {
                                $send_detail[$dk]['money'] = round($dv['price'] * $dv['num'], 2);
                            }
                            $send_data = [
                                'offer_detail_id' => $offer_detail_result_id,
                                'user_id'         => $project_log['user_id'],
                                'money'           => array_sum(array_column($send_detail, 'money')),
                                'detail'          => $send_detail,
                                'code'            => date('YmdHis') . rand(00000, 99999),
                                'send_time'       => $dose_value['week'],
                                'school_id'       => $dose_value['school_id'],
                            ];

                            $send_result    = Send::create($send_data);
                            $send_result_id = $send_result->id;
                        } else {
                            $send_detail = array_merge($send_detail, $find_send['detail']);
                            foreach ($send_detail as $dk => $dv) {
                                $send_detail[$dk]['money'] = round($dv['price'] * $dv['num'], 2);
                            }
                            $send_data = [
                                'offer_detail_id' => $offer_detail_result_id,
                                'user_id'         => $project_log['user_id'],
                                'money'           => array_sum(array_column($send_detail, 'money')),
                                'detail'          => $send_detail,
                                'code'            => date('YmdHis') . rand(00000, 99999),
                                'send_time'       => $dose_value['week'],
                                'school_id'       => $dose_value['school_id'],
                            ];

                            $send_result    = $find_send->save($send_data);
                            $send_result_id = $find_send->id;
                        }

                    }
                    if (! empty($send_detail0)) {
                        $find_send0 = Send::where('school_id', 0)->where('send_time', strtotime($dose_value['week']))->where('user_id', $project_log['user_id'])->findOrEmpty();
                        if ($find_send0->isEmpty()) {
                            foreach ($send_detail0 as $dk2 => $dv2) {
                                $send_detail0[$dk2]['money'] = round($dv2['price'] * $dv2['num'], 2);
                            }
                            $send_data0 = [
                                'offer_detail_id' => $offer_detail_result_id,
                                'user_id'         => $project_log['user_id'],
                                'money'           => array_sum(array_column($send_detail0, 'money')),
                                'detail'          => $send_detail0,
                                'code'            => date('YmdHis') . rand(00000, 99999),
                                'send_time'       => $dose_value['week'],
                                'school_id'       => 0,
                            ];

                            $send_result0    = Send::create($send_data0);
                            $send_result0_id = $send_result0->id;
                        } else {
                            $send_detail0 = array_merge($send_detail0, $find_send0['detail']);
                            foreach ($send_detail0 as $dk2 => $dv2) {
                                $send_detail0[$dk2]['money'] = round($dv2['price'] * $dv2['num'], 2);
                            }
                            $send_data0 = [
                                'offer_detail_id' => $offer_detail_result_id,
                                'user_id'         => $project_log['user_id'],
                                'money'           => array_sum(array_column($send_detail0, 'money')),
                                'detail'          => $send_detail0,
                                'code'            => date('YmdHis') . rand(00000, 99999),
                                'send_time'       => $dose_value['week'],
                                'school_id'       => 0,
                            ];

                            $send_result0    = $find_send0->save($send_detail0);
                            $send_result0_id = $find_send0->id;
                        }

                    }
                }

            }
            $school_id = array_unique($school_id);
            foreach ($school_id as $sk => $sv) {
                $offer_detail_list = OfferDetail::whereIn('id', $offer_detail_id)->where('school_id', $sv)->select()->toArray();
                $filter_detail     = array_column($offer_detail_list, 'detail');
                $twoDimArray       = [];

                // 遍历三维数组，将其转换为二维数组
                foreach ($filter_detail as $subArray) {
                    foreach ($subArray as $item) {
                        $twoDimArray[] = $item;
                    }
                }

                $filter_detail = $this->array_do($twoDimArray);

                $start_end  = getstart();
                $start      = $start_end['start'];
                $end        = $start_end['end'];
                $offer_data = [
                    'name'      => $start . '-' . $end . '报价单',
                    'money'     => array_sum(array_column($offer_detail_list, 'money')),
                    'detail'    => $filter_detail,
                    'school_id' => $sv,
                ];
                $offer                = Offer::create($offer_data);
                $offer_detail_id_list = array_column($offer_detail_list, 'id');
                OfferDetail::whereIn('id', $offer_detail_id_list)->update(['offer_id' => $offer->id]);
            }
        }

    }
    public function array_do3($array1, $array2)
    {
        $mergedArray = [];

        // Create a map for the first array using type_id as key
        $array1Map = [];
        foreach ($array1 as $item) {
            $typeId             = $item['type_id'];
            $array1Map[$typeId] = $item;
        }

        // Merge arrays based on type_id and only keep the merged ones
        foreach ($array2 as $item) {
            $typeId = $item['type_id'];
            if (isset($array1Map[$typeId])) {
                $mergedArray[] = array_merge($array1Map[$typeId], $item);
            }
        }

        return $mergedArray;
    }
    public function array_do($array)
    {
        $result = [];

        foreach ($array as $item) {
            $type_id = $item['type_id'];
            if (! isset($result[$type_id])) {
                $result[$type_id] = $item;
            } else {
                $result[$type_id]['num'] += $item['num'];
            }
        }

        $result = array_values($result);
        return $result;
    }
    public function array_do2($data)
    {
        $groupedData = [];

        foreach ($data as $item) {
            $school_id = $item['school_id'];
            $type_id   = $item['type_id'];
            $dose_id   = $item['dose_id'];
            $brand_id  = $item['brand_id'];
            $order_id  = $item['order_id'];
            $key       = $school_id . '-' . $type_id . '-' . $dose_id;

            if (! isset($groupedData[$key])) {
                $groupedData[$key] = $item;
            } else {
                $groupedData[$key]['num'] += $item['num'];
            }

        }
        $result = array_values($groupedData);
        return $result;
    }

}
